package com.mapler.job;

import com.mapler.autoresponder.service.CLAutoRUtil;
import com.mapler.autoresponder.service.EmailModel;
import com.mapler.model.SModel;
import com.mapler.service.INotifier;
import com.mapler.utility.HttpHelper;
import com.mapler.utility.IConstant;
import java.io.BufferedReader;
import java.io.StringReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.internet.MimeMessage;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;

/**
 *
 * @author mithun
 */
public class CLAutoREmailPuller implements Runnable {
    CLAutoRUtil autoRUtil;
    INotifier iNotifier;
    EmailModel emailModel;
    SModel sModel;
    
    @Override
    public void run() {
        try {
            autoRUtil = this.getAutoRUtil();
            emailModel.setAuto(false);
            ArrayList<MimeMessage> unReadEmails = autoRUtil.readEmail(emailModel, iNotifier);
            
            for (MimeMessage mimeMessage : unReadEmails) {
                this.saveEmail(mimeMessage);
            }
        } catch( Exception ex ) {
            ex.printStackTrace();
        }
    }
    
    private void saveEmail(MimeMessage message) {
        try {
            sModel = this.getsModel();
            StringBuilder buffer = new StringBuilder();
            
            if (message.getContent() instanceof Multipart) {
                Multipart mp = (Multipart) message.getContent();
                int count = mp.getCount();
                for (int j = 0; j < count; j++) {
                    String contentLine = mp.getBodyPart(j).getContent().toString();
                    buffer.append("> ");
                    buffer.append(contentLine);
                    buffer.append("\r\n");
                }
            } else {
                String content = (String) message.getContent();
                StringReader contentReader = new StringReader(content);
                BufferedReader br = new BufferedReader(contentReader);
                String contentLine;
                while ((contentLine = br.readLine()) != null) {
                    buffer.append("> ");
                    buffer.append(contentLine);
                    buffer.append("\r\n");
                }
            }
            StringBuilder request = new StringBuilder();
            request.append("<Request>");
            request.append("<username>").append(sModel.getUsername()).append("</username>");
            request.append("<password>").append(sModel.getPassword()).append("</password>");
            
            request.append("<subject>").append(message.getSubject()).append("</subject>");
            request.append("<body>").append(buffer.toString()).append("</body>");
            request.append("<from>").append(message.getFrom()[0]).append("</from>");
            request.append("<to>").append(message.getRecipients(Message.RecipientType.TO)[0]).append("</to>");
            request.append("<cc>").append("").append("</cc>");
            request.append("<bcc>").append("").append("</bcc>");
            request.append("</Request>");

            String req = URLEncoder.encode(request.toString(), "UTF-8");
            String uri = "http://" + IConstant.HOSTNAME + "/index.php?r=autoresponderEmail/addAccount";
            String param = "request=" + req;
            String response = HttpHelper.post(new URL(uri), param);

            Document document = DocumentHelper.parseText(response);
            String errorCode = document.valueOf("Response/errorcode");
            String msg = document.valueOf("Response/message");
        } catch (Throwable ex) {
            ex.printStackTrace();
        }
    }
    
    public CLAutoRUtil getAutoRUtil() {
        return autoRUtil;
    }

    public void setAutoRUtil(CLAutoRUtil autoRUtil) {
        this.autoRUtil = autoRUtil;
    }

    public INotifier getiNotifier() {
        return iNotifier;
    }

    public void setiNotifier(INotifier iNotifier) {
        this.iNotifier = iNotifier;
    }

    public EmailModel getEmailModel() {
        return emailModel;
    }

    public void setEmailModel(EmailModel emailModel) {
        this.emailModel = emailModel;
    }

    public SModel getsModel() {
        return sModel;
    }

    public void setsModel(SModel sModel) {
        this.sModel = sModel;
    }
}
